package com.chat.datea.ui;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.chat.datea.R;
import com.chat.datea.base.BaseActivity;
import com.chat.datea.service.IConstants;
import com.chat.datea.service.MusicInterface;
import com.chat.datea.service.MusicService;
import com.chat.datea.ui.playerDiscView.PlayerDiscView;
import com.chat.datea.utils.lrc.LyricAdapter;
import com.chat.datea.utils.lrc.LyricLoadHelper;
import com.chat.datea.utils.lrc.LyricSentence;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by YanBinXie on 15/11/2.
 */
public class MusicActivity extends BaseActivity implements View.OnClickListener, IConstants {
    private MusicInterface mi;
    TextView music_name, music_singer;
    MyServiceConn conn;
    private Timer timer;
    private SeekBar sb;
    private LyricAdapter lyricAdapter;
    private ImageView play, next, return_bt, previous, type, change;
    private PlayerDiscView mPlayerDiscView;
    private static final String modeName[] = {"列表循环", "顺序播放", "随机播放", "单曲循环"};
    private int modeDrawable[] = {R.drawable.bt_roundplay,
            R.drawable.bt_order, R.drawable.bt_random,
            R.drawable.bt_roundsingle};
    private int mCurMode;
    private ListView list_view;
    private TextView lyric_empty;
    private FrameLayout player_frame_content;
    private static LyricLoadHelper mLyricLoadHelper;
    private int changeDrawable[] = {R.drawable.bt_img,
            R.drawable.bt_text};
    private int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);

        initView();

        Intent intent = new Intent(this, MusicService.class);
        conn = new MyServiceConn();
        bindService(intent, conn, BIND_AUTO_CREATE);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = handler.obtainMessage();
                handler.sendMessage(message);
            }
        }, 0, 500);
    }

    private void initView() {
        music_name = (TextView) findViewById(R.id.music_name);
        sb = (SeekBar) findViewById(R.id.sb);
        play = (ImageView) findViewById(R.id.play);
        next = (ImageView) findViewById(R.id.next);
        return_bt = (ImageView) findViewById(R.id.return_bt);
        change = (ImageView) findViewById(R.id.change);
        previous = (ImageView) findViewById(R.id.previous);
        type = (ImageView) findViewById(R.id.type);
        mPlayerDiscView = (PlayerDiscView) findViewById(R.id.musics_player_disc_view);
        music_singer = (TextView) findViewById(R.id.music_singer);
        list_view = (ListView) findViewById(R.id.list_view);
        player_frame_content = (FrameLayout) findViewById(R.id.player_frame_content);
        player_frame_content.setVisibility(View.GONE);
        lyric_empty = (TextView) findViewById(R.id.lyric_empty);
        play.setOnClickListener(this);
        next.setOnClickListener(this);
        return_bt.setOnClickListener(this);
        previous.setOnClickListener(this);
        type.setOnClickListener(this);
        change.setOnClickListener(this);
        lyric_empty.setOnClickListener(this);
        lyricAdapter = new LyricAdapter(this);
        list_view.setEmptyView(lyric_empty);
        list_view.setAdapter(lyricAdapter);
        mLyricLoadHelper = new LyricLoadHelper();
        mLyricLoadHelper.setLyricListener(mLyricListener);
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //根据拖动的进度改变音乐播放进度
                int progress = seekBar.getProgress();
                if (mi != null) {
                    //改变播放进度
                    mi.seekTo(progress);

                }
                if (timer == null) {
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            Message message = handler.obtainMessage();
                            handler.sendMessage(message);
                        }
                    }, 0, 500);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {

            }
        });
    }


    private LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {

        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
            // Log.i(TAG, "onLyricLoaded");
            if (lyricSentences != null) {
                // Log.i(TAG, "onLyricLoaded--->歌词句子数目=" + lyricSentences.size()
                // + ",当前句子索引=" + index);
                lyricAdapter.setLyric(lyricSentences);
                lyricAdapter.setCurrentSentenceIndex(index);
                // 本方法执行时，lyricshow的控件还没有加载完成，所以延迟下再执行相关命令
                // mHandler.sendMessageDelayed(
                // Message.obtain(null, MSG_SET_LYRIC_INDEX, index, 0),
                // 100);
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            // Log.i(TAG, "onLyricSentenceChanged--->当前句子索引=" +
            // indexOfCurSentence);
            lyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            list_view.smoothScrollToPositionFromTop(indexOfCurSentence,
                    list_view.getHeight() / 2, 500);
        }
    };


    public static LyricLoadHelper getHelpter() {
        return mLyricLoadHelper;
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (mi != null) {
                music_name.setText(mi.getName());
                music_singer.setText(mi.getSinger());
                if (mi.getIsPlay()) {
                    sb.setMax(mi.getDuration());
                    sb.setProgress(mi.getProgress());
                    if (!mi.isDownload()) {
                        mLyricLoadHelper.notifyTime((long) mi.getProgress());
                    }
                }
                if (mi.getIsPlay()) {
                    play.setImageResource(R.drawable.bt_pause);
                    mPlayerDiscView.rePlay();

                } else {
                    play.setImageResource(R.drawable.bt_play);
                    mPlayerDiscView.pause();
                }
                mPlayerDiscView.loadAlbumCover(mi.getRadioUrl());
                mCurMode = mi.getmPlayMode();
                type.setImageResource(modeDrawable[mCurMode]);

            }
            return false;
        }
    });

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                if (mi.getIsPlay()) {
                    mi.pause();
                } else if (mi.getIsPlay() == false && mi.getDuration() > mi.getProgress()) {
                    mi.continuePlay();
                }
                break;
            case R.id.next:
                mi.next();
                mPlayerDiscView.next();
                break;
            case R.id.return_bt:
                finish();
                overridePendingTransition(R.anim.push_bottom_out_stop, R.anim.push_bottom_out);
                break;
            case R.id.previous:
                mi.playPrev();
                mPlayerDiscView.next();
                break;
            case R.id.type:
                changeMode();
                break;
            case R.id.change:
                if (i == 0) {
                    i++;
                    player_frame_content.setVisibility(View.VISIBLE);
                    mPlayerDiscView.setVisibility(View.GONE);
                    change.setImageResource(changeDrawable[0]);
                } else {
                    i = 0;
                    player_frame_content.setVisibility(View.GONE);
                    mPlayerDiscView.setVisibility(View.VISIBLE);
                    change.setImageResource(changeDrawable[1]);
                }
                break;
            case R.id.lyric_empty:
                mLyricLoadHelper.loadLyric(mi.getLyricFilePath());
                break;
        }
    }

    /**
     * 判断选择的循环方式
     **/
    private void changeMode() {
        mCurMode++;
        if (mCurMode > MPM_SINGLE_LOOP_PLAY) {
            mCurMode = MPM_LIST_LOOP_PLAY;
        }
        mi.setPlayMode(mCurMode);
        initPlayMode();
    }

    private void initPlayMode() {
        Toast.makeText(this, modeName[mCurMode], Toast.LENGTH_SHORT).show();
        type.setImageResource(modeDrawable[mCurMode]);
    }


    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mi = (MusicInterface) service;
            mLyricLoadHelper.loadLyric(mi.getLyricFilePath());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(R.anim.push_bottom_out_stop, R.anim.push_bottom_out);
        }
        return super.onKeyDown(keyCode, event);
    }
}
